<template>
  <view>
    <!-- 	<u-navbar :is-back="false" :background="navbarBackground" :height="navigationHeight">
			<view class="am-flex-rc-center navbar-slot-wrap"><image :src="NAV_BAR_TITLE" class="navbar-title-img"></image></view>
		</u-navbar> -->
    <view style="position: sticky; top: 0rpx; left: 0; z-index: 1">
      <view class="search-content">
        <view class="search-content-con">
          <u-search
            inputAlign="center"
            :placeholder="
              pageQuery.after == 'yes'
                ? '搜索'
                : '可搜索收货人姓名/电话/商品名称/订单号'
            "
            bg-color="#F7F8FA"
            v-model="keyword"
            :height="56"
            :maxlength="20"
            @search="headerSearchHandle"
            @custom="headerSearchHandle"
            :action-style="searchActionStyle"
          ></u-search>
        </view>
      </view>
      <u-tabs
        active-color="#ff5510"
        :list="pageQuery.after == 'yes' ? listSale : list"
        :is-scroll="true"
        :current="current"
        @change="change"
      ></u-tabs>
    </view>
    <view v-if="dataList.length" class="order-wrap">
      <view class="order-list" v-for="(item, index) in dataList" :key="index">
        <OrderCard
          :item="item"
          @orderPay="orderPay"
          @cancelOrder="cancelOrder"
          @applyRefund="applyRefund"
          @orderSign="orderSign"
          @cancelRefund="cancelRefund"
        ></OrderCard>
      </view>
    </view>
    <!-- <pay-panel ref="payPanelRef" @paySuccess="paySuccessCb" @payFail="payFailCb" scene="order"></pay-panel> -->
    <payment-method
      ref="paymentRef"
      @payFail="payFailCb"
      @paySuccess="paySuccessCb"
      :scene="payScene"
    ></payment-method>
    <co-load-more :type="loadingType"
      ><co-empty slot="empty" model="data" paddingTop="80rpx"></co-empty
    ></co-load-more>
  </view>
</template>

<script>
// import { navigationHeight, navBarHeight } from '@/utils/systemInfo.js';
import OrderCard from './components/order-card'
// import { NAV_BAR_TITLE } from '@/types/navbar.js';
import {
  apiOrderList,
  apiCancelOrder,
  apiApplyRefund,
  apiOrderSign,
  apiCancelRefund,
  apiSalesOrderList
} from '@/api/order'
import { UPDATE_ORDER_LIST } from '@/types/globalEventName'
// 不允许请求的type
const noRequestType = [1, 2, 3]

const cacheTime = 5 * 60 * 1000 // 缓存数据的时间，单位ms; 5分钟。
export default {
  data() {
    return {
      // navbarBackground: {
      // 	background: 'linear-gradient(180deg, #65DC5F 0%, #52C41A 100%)'
      // },
      // navigationHeight,
      // NAV_BAR_TITLE,
      // navBarHeight,
      keyword: '',
      realSearchKeyword: '',
      dataList: [],
      pageNum: 1,
      loadingType: 999,
      lastGetTime: 0, // 上次请求数据的时间；时间戳
      pageQuery: {},
      current: 0,
      searchActionStyle: {
        color: '#fff',
        fontSize: '28rpx',
        background:
          'linear-gradient( 323deg, #FF4564 8%, #F14141 30%, #FC843B 100%)',
        borderRadius: '200rpx 200rpx 200rpx 200rpx',
        width: '112rpx',
        height: '56rpx',
        lineHeight: '56rpx'
      },
      list: [
        {
          name: '全部订单',
          id: ''
        },
        {
          name: '待支付',
          id: '-1'
        },
        {
          name: '待接单',
          id: '0'
        },
        {
          name: '派送中',
          id: '1'
        },
        {
          name: '已完成',
          id: '2'
        },
        {
          name: '交易关闭',
          id: '5'
        }
      ],
      listSale: [
        {
          name: '全部订单',
          id: ''
        },
        {
          name: '售后中',
          id: '3'
        },
        {
          name: '已退款',
          id: '4'
        },
        {
          name: '拒绝退款',
          id: '7'
        }
      ]
    }
  },
  components: {
    OrderCard
  },
  /**
   * @param {Object} options
   * @param {String} options.status - 非必填。订单状态
   * @param {String} options.after [yes | undefined]- 非必填。是否查询售后订单
   * */
  onLoad(options) {
    this.pageQuery = options
    this.setPageTitle(options.status)
    let arr = this.pageQuery.after == 'yes' ? this.listSale : this.list
    arr.forEach((e, i) => {
      if (e.id == options.status) {
        this.current = i
      }
    })
    // this.getInit()
    uni.$on(UPDATE_ORDER_LIST, this.updateOrderCb)
  },
  onUnload() {
    uni.$off(UPDATE_ORDER_LIST, this.updateOrderCb)
  },
  onShow() {
    // 缓存一段时间再请求
    if (Date.now() > this.lastGetTime + cacheTime) {
      this.getInit()
    }
  },
  onReachBottom() {
    this.getOrderList()
  },
  onPullDownRefresh() {
    this.getInit()
  },
  methods: {
    change(index) {
      this.current = index
      this.pageNum = 1
      this.dataList = []
      if (this.pageQuery.after == 'yes') {
        this.pageQuery.status = this.listSale[index].id
        this.getSalesOrder()
      } else {
        this.pageQuery.status = this.list[index].id

        this.getStatusOrder()
      }
    },
    setPageTitle(status) {
      if (typeof this.pageQuery.status !== 'undefined') {
        let obj = {
          '-1': '待支付',
          0: '待接单',
          2: '已完成',
          5: '交易关闭',
          1: '派送中'
        }
        let objTitle = status ? obj[status] : ''
        uni.setNavigationBarTitle({
          title: objTitle || '我的订单'
        })
      } else if (this.pageQuery.after === 'yes') {
        uni.setNavigationBarTitle({
          title: '退款/售后'
        })
      } else {
        uni.setNavigationBarTitle({
          title: '我的订单'
        })
      }
    },
    updateOrderCb() {
      this.lastGetTime = 0
    },
    getInit() {
      this.pageNum = 1
      this.loadingType = 999
      this.dataList = []
      this.getOrderList()
    },
    getOrderList() {
      if (noRequestType.includes(this.loadingType)) {
        return
      }
      this.loadingType = 2
      console.log('调用获取数据')
      if (this.pageQuery.after === 'yes') {
        this.getSalesOrder()
      } else {
        this.getStatusOrder()
      }
    },
    getStatusOrder() {
      apiOrderList({
        keyword: this.realSearchKeyword,
        pageNum: this.pageNum,
        pageSize: 10,
        status: this.pageQuery.status || ''
      })
        .then(({ data }) => {
          if (data.state === 'OK') {
            this.lastGetTime = Date.now()
            if (this.pageNum === 1) {
              this.dataList = data.data.list
            } else {
              this.dataList = [...this.dataList, ...data.data.list]
            }
            if (this.pageNum === 1 && this.dataList.length === 0) {
              this.loadingType = 1
            } else if (data.data.lastPage) {
              this.loadingType = 3
            } else {
              this.loadingType = 999
              this.pageNum++
            }
          } else {
            this.loadingType = 999
            this.$am_toast.warning(data.msg)
          }
          uni.stopPullDownRefresh()
        })
        .catch((err) => {
          console.log(err)
          this.loadingType = 999
          this.$am_toast.warning('查询失败，请重新尝试！')
          uni.stopPullDownRefresh()
        })
    },
    getSalesOrder() {
      apiSalesOrderList({
        keyword: this.realSearchKeyword,
        pageNum: this.pageNum,
        pageSize: 10,
        status: this.pageQuery.status || ''
      })
        .then(({ data }) => {
          if (data.state === 'OK') {
            this.lastGetTime = Date.now()
            if (this.pageNum === 1) {
              this.dataList = data.data.list
            } else {
              this.dataList = [...this.dataList, ...data.data.list]
            }
            if (this.pageNum === 1 && this.dataList.length === 0) {
              this.loadingType = 1
            } else if (data.data.totalPage === this.pageNum) {
              this.loadingType = 3
            } else {
              this.loadingType = 999
              this.pageNum++
            }
          } else {
            this.loadingType = 999
            this.$am_toast.warning(data.msg)
          }
          uni.stopPullDownRefresh()
        })
        .catch((err) => {
          console.log(err)
          this.loadingType = 999
          this.$am_toast.warning('查询失败，请重新尝试！')
          uni.stopPullDownRefresh()
        })
    },
    headerSearchHandle(e) {
      this.getInit()
    },
    // 点击付款
    orderPay(item) {
      console.log(item)
      this.$refs.paymentRef.pay_out([item.oid])
    },
    // 支付成功
    paySuccessCb() {
      this.getInit()
      uni.navigateTo({
        url: '/pages/place-order/pay-result'
      })
    },
    cancelOrder(item) {
      apiCancelOrder(item)
        .then((res) => {
          let { state, msg } = res.data
          if (state === 'OK') {
            this.getInit()
            this.$am_toast.success(msg)
          } else {
            this.$am_toast.warning(msg)
          }
        })
        .catch(() => {
          this.$am_toast.error('操作失败，请重新尝试！')
        })
    },
    // 支付失败
    payFailCb(p_data) {
      if (p_data.type === 'not_enough_stop') {
        this.$am_toast.warning(p_data.msg)
      }
    },
    // 申请退款
    applyRefund(item) {
      apiApplyRefund(item)
        .then((res) => {
          let { state, msg } = res.data
          if (state === 'OK') {
            this.getInit()
            this.$am_toast.success(msg)
          } else {
            this.$am_toast.warning(msg)
          }
        })
        .catch(() => {
          this.$am_toast.error('操作失败，请重新尝试！')
        })
    },
    // 确认签收
    orderSign(item) {
      uni.showModal({
        title: '签收商品',
        content: '确定您已收到当前商品吗?',
        confirmColor: '#4BB019',
        success: (cancelRes) => {
          if (cancelRes.confirm) {
            uni.showLoading({
              mask: true
            })
            apiOrderSign({ oid: item.oid })
              .then((res) => {
                let { state, msg } = res.data
                uni.hideLoading()
                if (state === 'OK') {
                  this.getInit()
                } else {
                  this.$am_toast.warning(msg)
                }
              })
              .catch(() => {
                uni.hideLoading()
                this.$am_toast.error('操作失败，请重新尝试！')
              })
          }
        }
      })
    },
    // 撤销售后申请
    cancelRefund(item) {
      uni.showModal({
        title: '撤销申请',
        content: '确定撤销当前商品的售后申请？',
        confirmColor: '#4BB019',
        success: (cancelRes) => {
          if (cancelRes.confirm) {
            uni.showLoading({
              mask: true
            })
            apiCancelRefund({ oid: item.oid })
              .then((res) => {
                let { state, msg } = res.data
                uni.hideLoading()
                if (state === 'OK') {
                  this.$am_toast.success('撤销成功')
                  this.getInit()
                } else {
                  this.$am_toast.warning(msg)
                }
              })
              .catch(() => {
                uni.hideLoading()
                this.$am_toast.error('操作失败，请重新尝试！')
              })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
$page-plr: 16rpx;
.navbar-slot-wrap {
  position: absolute;
  width: 750rpx;
  left: 0;
}
.navbar-title-img {
  display: block;
  width: 162rpx;
  height: 40rpx;
}
.order-wrap {
  padding: 16rpx;
}
.order-list {
  & + .order-list {
    margin-top: 16rpx;
  }
}
.search-content {
  border-bottom: 2rpx solid #f5f5f5;
  display: flex;
  align-items: center;
  padding: 32rpx 24rpx;
  background-color: #fff;
}
.search-content-con {
  flex: 1;
}
</style>
